package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import com.sky.exception.AddDataException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 自定义切面类，实现公共字段自我填充
 */

@Slf4j
@Aspect
@Component
public class AutoFillAspect {
	
	/**
	 * 切入点
	 */
	@Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
	public void autoFillPointCut() {}
	
	/**
	 * 前置通知 在接口请求到数据库之前设定
	 */
	@Before("autoFillPointCut()")
	public void autoFill(JoinPoint joinPoint) {
		log.info("开始进行公共字段填充...");
		// 获取到方法上数据库操作类型
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();   // 获取方法类型
		OperationType value = signature.getMethod().getAnnotation(AutoFill.class).value(); // 获取注解对象的操作类型
		
		// 获取方法的参数-实体对象
		Object[] args = joinPoint.getArgs();
		if (args == null || args.length == 0) {
			return;
		}
		// 准备数据
		LocalDateTime now = LocalDateTime.now();
		Long id = BaseContext.getCurrentId();
		// 为公共字段赋值
		try {
			Method updateTime = args[0].getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
			Method updateUser = args[0].getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
			updateTime.invoke(args[0], now);
			updateUser.invoke(args[0], id);
		} catch (Exception e) {
			throw new AddDataException("Error creating:" + e.getMessage());
		}
		// 根据对应的操作数值
		if (value == OperationType.INSERT) {
			try {
				Method createTime = args[0].getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,
					LocalDateTime.class);
				Method createUser = args[0].getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
				createTime.invoke(args[0], now);
				createUser.invoke(args[0], id);
			} catch (Exception e) {
//				throw new RuntimeException(e);
				throw new AddDataException("Error creating:" + e.getMessage());
			}
		}
		
	}
}
